/*
 * Copyright 2014 François Rajchenbach.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package qmd.rgo.format;

import java.io.BufferedWriter;
import java.io.IOException;

/**
 * A context object returned by the API when the next step is to add an item to
 * the current JSON array, or to indicate that all items have been defined.
 *
 * @param <T>
 *            The type of the context object to be returned after the array is
 *            complete
 * 
 * @author François Rajchenbach
 * @since 1.0
 */
public final class ArrayContext<T> {

	private final T previousContext;
	private final BufferedWriter writer;
	private boolean empty;

	protected ArrayContext(final T argPreviousContext,
			final BufferedWriter argWriter) {
		previousContext = argPreviousContext;
		writer = argWriter;
		empty = true;
	}

	/**
	 * Starts defining a new item to the current array.
	 * 
	 * @return The context object to set the value of the new item
	 * @throws IOException
	 *             If an I/O error occurs
	 */
	public ValueContext<ArrayContext<T>> itemHaving() throws IOException {
		if (!empty) {
			writer.write(',');
		}
		empty = false;
		return new ValueContext<ArrayContext<T>>(this, writer);
	}

	/**
	 * @return The context object after the array is complete
	 * @throws IOException
	 *             If an I/O error occurs
	 */
	public T noMoreItem() throws IOException {
		writer.write(']');
		return previousContext;
	}

}
